#include "TcpSocket.h"

bool TcpSocket::Connect(std::string host, uint32_t port)
{
    struct sockaddr_in servaddr; // 定义服务器地址结构体
    // 创建客户端套接字文件
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    // 初始化服务器端口地址
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, host.c_str(), &servaddr.sin_addr);
    servaddr.sin_port = htons(port);
    int con_res = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    if (con_res == -1)
    {
        return false;
    }

    return true;
}

void TcpSocket::OnClose()
{
    close(sockfd);
}

int TcpSocket::SendBuffer(const void *buf, int len)
{
    return send(sockfd, buf, len, 0);
}

int TcpSocket::RecvBuffer(void *buf, int len)
{
    return recv(sockfd, buf, len, 0);
}
